/*
 * Copyright (C) 2018 Zhejiang xiaominfo Technology CO.,LTD.
 * All rights reserved.
 * Official Web Site: http://www.xiaominfo.com.
 * Developer Web Site: http://open.xiaominfo.com.
 */

package com.github.xiaoymin.gateway.repository;

import cn.hutool.core.collection.CollectionUtil;
import com.github.xiaoymin.gateway.core.pojo.ServiceRoute;
import com.github.xiaoymin.gateway.spring.support.CloudSetting;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/***
 * 基于本地配置的方式动态聚合云端(http)任意OpenAPI
 * @since:servlet-gateway-spring-boot-starter 1.0
 * @author <a href="mailto:xiaoymin@foxmail.com">xiaoymin@foxmail.com</a> 
 * 2020/10/29 20:11
 */
public class CloudRepository extends AbsctractRepository{

    private final CloudSetting cloudSetting;

    public CloudRepository(CloudSetting cloudSetting){
        this.cloudSetting=cloudSetting;
        if (cloudSetting!=null&&CollectionUtil.isNotEmpty(cloudSetting.getRoutes())){
            cloudSetting.getRoutes().stream().forEach(cloudRoute -> {
                routeMap.put(cloudRoute.pkId(),new ServiceRoute(cloudRoute));
            });
        }
    }

    public CloudSetting getCloudSetting() {
        return cloudSetting;
    }

    @Override
    public Optional<ServiceRoute> applyServiceRoute(HttpServletRequest httpServletRequest) {
        List<ServiceRoute> serviceRoutes=getRoutes();
        if (CollectionUtil.isNotEmpty(serviceRoutes)){
            ServiceRoute serviceRoute=null;
            for (ServiceRoute route:serviceRoutes){
                if (checkRoute(route,httpServletRequest)){
                    serviceRoute=route;
                    break;
                }
            }
            return Optional.ofNullable(serviceRoute);
        }
        return Optional.empty();
    }
}
